package com.hmdp.controller;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.service.IShopTypeService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {
    @Resource
    private IShopTypeService typeService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @GetMapping("list")
    public Result queryTypeList() {
        //这里的列表是多个对象，考虑使用List
        //1.从redis查询分类列表缓存
        List<String> plateList = stringRedisTemplate.opsForList().range("plate:list:", 0, -1);
        List<ShopType> shopTypeList = new ArrayList<>();
        List<String> temp = new ArrayList<>();
        //2.判断是否存在
        if (!plateList.isEmpty()){
            //3.存在，直接返回（把json字符串转换成java对象返回）
            for (String s : plateList) {
                shopTypeList.add(JSONUtil.toBean(s, ShopType.class));
            }
            return Result.ok(shopTypeList);
        }
        //4.不存在，工具id查询数据库
        List<ShopType> typeList = typeService
                .query().orderByAsc("sort").list();
        //5.数据没有该数据。返回错误(shop.null判断是都为空的快捷方式)
        if (typeList.isEmpty()){
            return Result.fail("数据库的列表为空");
        }
        //6.数据库有该数据，写入redis
        stringRedisTemplate.delete("plate:list:");
        for (ShopType shopType : typeList) {
            temp.add(JSONUtil.toJsonStr(shopType));
        }
        stringRedisTemplate.opsForList().rightPushAll("plate:list:", temp);
        stringRedisTemplate.expire("plate:list:",CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(typeList);
    }
}
